package com.gmlive.gradle

import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.tasks.TaskAction
import org.gradle.internal.os.OperatingSystem

class ReinforceTask extends DefaultTask {
    ReinforceExtension configuration
    def android

    def buildConfigs = []

    ReinforceTask() {
        group = 'reinforce'
        description = "AiJiaMi jiagu task"

        android = project.extensions.android
        configuration = project.reinforceConfig

        if (!project.plugins.hasPlugin('com.android.application')) {
            throw new GradleException('generateARGApk: Android Application plugin required')
        }

        android.applicationVariants.all { variant ->
            variant.outputs.each { output ->
                // remove reinforce
                String variantName = this.name["reinforce".length()..-1]
                if (variantName.equalsIgnoreCase(variant.buildType.name as String) || isTargetFlavor(variantName,
                        variant.productFlavors, variant.buildType.name)) {
                    def outputFile = null
                    try {
                        if (variant.metaClass.respondsTo(variant, "getPackageApplicationProvider")) {
                            outputFile = new File(variant.packageApplicationProvider.get().outputDirectory, output.outputFileName)
                        }
                    } catch (Exception ignore) {
                        // no-op
                    } finally {
                        outputFile = outputFile ?: output.outputFile
                    }

                    def variantInfo = null
                    if (variant.variantData.hasProperty("variantConfiguration")) {
                        variantInfo = variant.variantData.variantConfiguration
                    } else {
                        variantInfo = variant.variantData.variantDslInfo
                    }

                    buildConfigs << new BuildOptions(
                            outputFile,
                            variantInfo.signingConfig,
                            variantInfo.applicationId,
                            variant.buildType.name,
                            variant.productFlavors
                    )
                }
            }
        }
    }

    @TaskAction
    void run() {
        println("[AiJiaMi] >>> configuartion:$configuration")
        println("[AiJiaMi] >>> BuildConfigs:$buildConfigs")

        buildConfigs.each { buildOptions ->
            // runJiaGuTask(buildOptions)
            execAiJiaMeTask(buildOptions)
        }
    }

    // 执行加固任务
    def runJiaGuTask(buildOptions) {
        println("[JiaGu360] current system = ${OperatingSystem.current().name}")
        // 加固工具目录
        String jiaGuToolsDir = "${project.projectDir}/${configuration.jiaGuToolPath}/${getJiaGuToolsDir()}"

        // 360加固 账号登录
        project.exec {
            workingDir = "${jiaGuToolsDir}"
            executable = 'java'
            args = ['-jar', 'jiagu.jar', '-login', "${configuration.userName}", "${configuration.password}"]
        }.assertNormalExitValue()

        // 设置签名
        project.exec {
            workingDir = "${jiaGuToolsDir}"
            executable = 'java'
            args = ['-jar', 'jiagu.jar', '-importsign', "${buildOptions.sign.storeFile}",
                    "${buildOptions.sign.storePassword}", "${buildOptions.sign.keyAlias}",
                    "${buildOptions.sign.keyPassword}"]
        }.assertNormalExitValue()

        // 加固配置信息
        project.exec {
            workingDir = "${jiaGuToolsDir}"
            executable = 'java'
            args = ['-jar', 'jiagu.jar', '-showconfig']
        }.assertNormalExitValue()

        // 加固apk
        def resguardSignedAlignedApk = new File(findTargetApk(project, buildOptions.outputFile, buildOption.sign.v2SigningEnabled))
        println("[JiaGu360] 目标apk路径:${resguardSignedAlignedApk}")
        project.exec {
            workingDir = "${jiaGuToolsDir}"
            executable = 'java'
            args = ['-jar', 'jiagu.jar', '-jiagu', "${resguardSignedAlignedApk}",
                    "${reinforceFolder(buildOptions.outputFile)}", '-autosign']
        }.assertNormalExitValue()
    }

    def execAiJiaMeTask(buildOption) {
        println('[AiJiaMi] >>> 开始执行爱加密')
        // 爱加密加固jar包路径
        String aiJiaMiToolPath = "${project.projectDir}/${configuration.jiaGuToolPath}"
        println("[AiJiaMi] >>> jar路径: ${aiJiaMiToolPath}")
        // 加固apk
        def targetApkPath = new File(findTargetApk(project, buildOption.outputFile, buildOption.sign.v2SigningEnabled))
        println("[AiJiaMi] >>> apk路径:${targetApkPath}")
        project.exec {
            executable = 'java'
            args = ['-jar',
                    "${aiJiaMiToolPath}",               // 加密工具
                    'http://192.168.40.20:10331/api',   // 加密平台
                    "${configuration.userName}",        // 平台登录用户名
                    "${targetApkPath}",                 // 目标apk路径
                    "${buildOption.outputFile.parent}", // 加密后apk输出目录
                    "${buildOption.outputFile.name[0..-5]}_aijiami.apk", // 加密后apk文件名
                    '', // 默认不知含义参数
                    "${buildOption.sign.keyAlias}", // 签名别名
                    '1', // 默认参数
                    "${configuration.encryptionId}", // 加固方案id
                    '', // 默认参数
                    ''  // 默认参数
            ]
        }
    }

    static isTargetFlavor(variantName, flavors, buildType) {
        if (flavors.size() > 0) {
            String flavor = flavors.get(0).name
            return variantName.equalsIgnoreCase(flavor) || variantName.equalsIgnoreCase([flavors.collect { it.name }.join(""), buildType].join(""))
        }
        return false
    }

    // 找到AndResGuard生成的apk文件
    static findTargetApk(project, outputFile, isV2Signing) {
        // remove apk
        def fileName = outputFile.name[0..-5]
        def andResGuardDir
        if (project.plugins.hasPlugin("AndResGuard")) {
            andResGuardDir = "${outputFile.parent}/AndResGuard_${fileName}"
            if (isV2Signing) {
                return "${andResGuardDir}/${fileName}_aligned_signed.apk"
            } else {
                return "${andResGuardDir}/${fileName}_signed_aligned.apk"
            }
        } else {
            return  "${outputFile.absolutePath}"
        }
    }

    // 暂用源文件目录
    static reinforceFolder(outputFile) {
        return "${outputFile.parent}"
    }

    static getJiaGuToolsDir() {
        if (OperatingSystem.current().isMacOsX()) {
            return "macOs"
        }

        if (OperatingSystem.current().isWindows()) {
            return "windows"
        }

        return "linux"
    }
}
